package com.xqy.wexmini.config;

import com.xqy.wexmini.filter.JwtAuthenticationTokenFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //权限异常处理器
    //@Autowired
    //private AccessDeniedHandler accessDeniedHandler;

    //认证处理异常类
    //@Autowired
    //private AuthenticationEntryPoint authenticationEntryPoint;

    //引入jwt拦截器

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;


    //加密密码，必须加密
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    //获得authenticationManager对象
    @Bean
    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }
    //很多认证的方法
    //关于安全框架的配置一般都在这里面配置
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                //关闭csrf
                .csrf().disable()
                //不通过Session获取SecurityContext
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                .authorizeRequests()
                // 对于登录接口 允许匿名访问
                .antMatchers("/login","/Logon","/swagger-resources/**","/webjars/**","/v2/**","/swagger-ui.html/**","/doc.html/**","/load").anonymous()
                // 除上面外的所有请求全部需要鉴权认证
                .anyRequest().authenticated();
        //添加过滤器
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //配置异常处理器
        //http.exceptionHandling()
                //认证失败处理器
                //.authenticationEntryPoint(authenticationEntryPoint)
                //授权失败处理器
                //.accessDeniedHandler(accessDeniedHandler);

        //允许跨域
        http.cors();
    }
}
